﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Hopscotch.Presentation.Common.Threading;

namespace Hopscotch.Test.Presentation.Threading
{
    public class DeterministicDispatcher : IDispatcher
    {
        private readonly Queue<Task> actions;

        public DeterministicDispatcher()
        {
            actions = new Queue<Task>();
        }

        public int ThreadId
        {
            get { return 0; }
        }

        public string ThreadName
        {
            get { return typeof(DeterministicDispatcher).Name; }
        }

        public bool CheckAccess()
        {
            return false;
        }

        public void Invoke(Action method)
        {
            method.Invoke();
        }

        public Task RunAsync(Action method)
        {
            Task task = new Task(method);
            actions.Enqueue(task);

            return task;
        }

        public void RunAllTasks()
        {
            while(actions.Count > 0)
            {
                Task task = actions.Dequeue();
                task.Start();
                task.Wait();
            }
        }
    }
}
